<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogVisible">添加角色</el-button>
                </el-col>
            </el-row >
             <el-table :data="roleslist" border stripe style="width: 100%">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbuttom', i1 == 0 ? 'bdtop' : '','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="deleteTag(scope.row,item1.id)">
                                {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <el-row :class="[i2 == 0 ? '' : 'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <el-col :span="5">
                                        <el-tag type="success" closable @close="deleteTag(scope.row,item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="19">
                                        <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="deleteTag(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialogVisible(scope.row.id)">编辑</el-button>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scope.row.id)">删除</el-button>
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色 -->
        <el-dialog title="添加角色" :visible.sync="addFormVisible" width="50%" @close="handleClose">
            <el-form :model="addForm" :rules="addFormRules" ref="addRuleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input type="text" v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input type="text" v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 编辑角色 -->
        <el-dialog title="编辑角色" :visible.sync="editFormVisible" width="50%" @close="editHandleClose">
            <el-form :model="editForm" :rules="editFormRules" ref="editRuleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input type="text" v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input type="text" v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoles">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 分配权限 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisble" width="50%" @close="setRightClose">
            <el-tree ref="tree" :data="rightslist" show-checkbox :props="defaultProps" node-key="id" default-expand-all 
            :default-checked-keys="defkeys">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisble = false">取 消</el-button>
                <el-button type="primary" @click="setRoles">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            roleslist:[],
            addForm:{
                roleName:'',
                roleDesc:''
            },
            addFormVisible:false,
            addFormRules:{
                roleName:[
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc:[
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
                ]
            },
            editForm:{},
            editFormVisible:false,
            editFormRules:{
                roleName:[
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc:[
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
                ]
            },
            setRightDialogVisble:false,
            rightslist:[],
            defaultProps:{
                children: 'children',
                label: 'authName'
            },
            defkeys:[],
            rolesId:''
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
       async getRolesList(){
           const {data:res} = await this.$http.get('roles')
           if(res.meta.status !== 200) {
               return this.$message.error('角色列表获取失败！')
           }
           this.roleslist = res.data
        },
        handleClose(){
            this.$refs.addRuleForm.resetFields()
        },
        addDialogVisible(){
            this.addFormVisible = true
        },
        // 添加角色
        addRoles(){
            this.$refs.addRuleForm.validate(async valid => {
                const {data:res} = await this.$http.post('roles',this.addForm)
                if(res.meta.status !== 201) {
                    return this.$message.error('添加失败！')
                }
                this.addFormVisible = false
                this.getRolesList()
                this.$message({
                    message: '添加成功！',
                    type: 'success'
                });
            }) 
        },
       async editDialogVisible(id){
            const {data:res} = await this.$http.get('roles/' + id)
            if(res.meta.status !== 200) {
               return this.$message.error('角色获取失败！')
            }
            this.editForm = res.data
            this.editFormVisible = true
        },
        editHandleClose(){
            this.$refs.editRuleForm.resetFields()
        },
        // 编辑修改角色
        editRoles(){
            this.$refs.editRuleForm.validate(async valid => {
                const {data:res} = await this.$http.put('roles/' + this.editForm.roleId,{roleName:this.editForm.roleName,roleDesc:this.editForm.roleDesc})
                if(res.meta.status !== 200) {
                    return this.$message.error('编辑失败！')
                }
                this.editFormVisible = false
                this.getRolesList()
                this.$message({
                    message: '编辑成功！',
                    type: 'success'
                });
            }) 
        },
        // 删除角色
        deleteRoles(id){
            this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async () => {
            await this.$http.delete('roles/'+id)
            this.getRolesList()
            this.$message({
                type: 'success',
                message: '删除成功!'
            });
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
        },
        // 分配权限
        async showSetRightDialog(role){
           const {data:res} = await this.$http.get('rights/tree')
           this.rightslist = res.data
           this.rolesId = role.id
           this.getDefKeys(role,this.defkeys)
           this.setRightDialogVisble = true       
        },
        getDefKeys(node, arr){
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach(item =>  this.getDefKeys(item,arr));
            
        },
        setRightClose(){
            this.defkeys = []
        },
       async setRoles(){
           const keys = [...this.$refs.tree.getCheckedKeys(),...this.$refs.tree.getHalfCheckedKeys()]
           const idStr = keys.join(',')
            const {data:res} = await this.$http.post(`roles/${this.rolesId}/rights`,{rids:idStr})
            if(res.meta.status !== 200){
                return this.$message.error('授权失败！')
            }
            this.getRolesList()
            this.setRightDialogVisble = false
            this.$message({
                type: 'success',
                message: '角色授权成功!'
            });
        },
        // 删除权限标签
        deleteTag(role,rightid){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
           const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
          this.$message({
            type: 'success',
            message: '取消权限成功!'
          });
          role.children = res.data
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
    border-top: 1px solid #eee;
}
.bdbuttom{
    border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>